package com.lrkj.property.service.impl;

import com.lrkj.common.annotation.DataScope;
import com.lrkj.common.constant.OrgConstants;
import com.lrkj.common.constant.PropertyConstants;
import com.lrkj.common.core.domain.entity.OrgTree;
import com.lrkj.common.exception.BaseException;
import com.lrkj.common.utils.DateUtils;
import com.lrkj.common.utils.SecurityUtils;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.common.utils.uuid.IdUtils;
import com.lrkj.framework.utils.NumberUtils;
import com.lrkj.property.domain.Community;
import com.lrkj.property.domain.Floor;
import com.lrkj.property.domain.Room;
import com.lrkj.property.domain.Unit;
import com.lrkj.property.mapper.UnitMapper;
import com.lrkj.property.service.ICommunityService;
import com.lrkj.property.service.IFloorService;
import com.lrkj.property.service.IRoomService;
import com.lrkj.property.service.IUnitService;
import com.lrkj.property.vo.UnitVo;
import com.lrkj.system.service.IOrgTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 单元信息Service业务层处理
 *
 * @author yajun_ren
 * @date 2021-07-22
 */
@Service
public class UnitServiceImpl implements IUnitService {
    @Autowired
    private UnitMapper unitMapper;

    @Autowired
    private IOrgTreeService orgTreeService;

    @Autowired
    private IFloorService iFloorService;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private ICommunityService communityService;

    /**
     * 查询单元信息
     *
     * @param id 单元信息ID
     * @return 单元信息
     */
    @Override
    public Unit selectUnitById(String id) {
        return unitMapper.selectUnitById(id);
    }

    /**
     * 查询单元信息列表
     *
     * @param unit 单元信息
     * @return 单元信息
     */
    @Override
    @DataScope(deptAlias = "t")
    public List<Unit> selectUnitList(Unit unit) {
        return unitMapper.selectUnitList(unit);
    }

    /**
     * 新增单元信息
     *
     * @param unit 单元信息
     * @return 结果
     */
    @Override
    public int insertUnit(Unit unit) {
        unit.setId(IdUtils.simpleUUID());
        unit.setCreateBy(SecurityUtils.getUsername());
        unit.setCreateTime(DateUtils.getNowDate());
        this.setUnitInfo(unit);
        return unitMapper.insertUnit(unit);
    }

    /**
     * 修改单元信息
     *
     * @param unit 单元信息
     * @return 结果
     */
    @Override
    public int updateUnit(Unit unit) {
        this.setUnitInfo(unit);
        unit.setUpdateBy(SecurityUtils.getUsername());
        unit.setUpdateTime(DateUtils.getNowDate());
        return unitMapper.updateUnit(unit);
    }

    /**
     * 批量删除单元信息
     *
     * @param ids 需要删除的单元信息ID
     * @return 结果
     */
    @Override
    public int deleteUnitByIds(String[] ids) {
        for (String unitId : ids) {
            this.deleteVerify(unitId);
        }
        orgTreeService.deleteOrgTreeByIds(ids);
        return unitMapper.deleteUnitByIds(ids);
    }

    /**
     * 删除单元信息信息
     *
     * @param id 单元信息ID
     * @return 结果
     */
    @Override
    public int deleteUnitById(String id) {
        this.deleteVerify(id);
        orgTreeService.deleteOrgTreeById(id);
        return unitMapper.deleteUnitById(id);
    }

    @Override
    public int doSaveList(List<Unit> saveBeans) {
        return unitMapper.doSaveList(saveBeans);
    }

    @Override
    public int selectCount(Unit unit) {
        return unitMapper.selectCount(unit);
    }


    private void setUnitInfo(Unit bean) {
        Floor parentBean = iFloorService.selectFloorById(bean.getFloorId());
        bean.setAncestors(parentBean.getAncestors() + "," + bean.getFloorId());
        bean.setDeptId(parentBean.getDeptId());
        OrgTree orgTree = new OrgTree();
        orgTree.setId(bean.getId());
        orgTree.setName(bean.getUnitName());
        orgTree.setParentId(bean.getFloorId());
        orgTree.setModelType(OrgConstants.room);
        orgTree.setAncestors(bean.getAncestors());
        orgTree.setOrderNum(Integer.valueOf(bean.getUnitNum()));
        orgTreeService.insertOrgTree(orgTree);
    }

    /***
     * 删除单元信息,校验关联信息
     *
     * **/
    private void deleteVerify(String unitId) {
        Room eg = new Room();
        eg.setUnitId(unitId);
        int count = roomService.selectCount(eg);
        if (count > 0) {
            throw new BaseException("删除单元失败,请先删除关联的房屋信息!");
        }
    }


    @Override
    @Transactional
    public int addUnitNum(UnitVo unitVo) {
        this.checkParams(unitVo);
        List<Unit> saveUnits = new ArrayList<>();
        Floor floor = iFloorService.selectFloorById(unitVo.getFloorId());
        Community community = communityService.selectCommunityById(floor.getCommunityId());
        //1、获取当前楼单元最大编号
        int maxUnitNum = unitMapper.maxUnitNum(unitVo.getFloorId());
        // 根据楼栋生成 房屋编号
        AtomicInteger roomNum = new AtomicInteger(0);
        //按照楼统一编排
        if (floor.getRoomRule().equals(PropertyConstants.room_rule_10)) {
            roomNum.set(roomService.maxRoomNum(unitVo.getFloorId()));
        }
        //2、创建楼栋信息
        for (Integer i = 0; i < unitVo.getUnitNum(); i++) {
            //通过楼栋表回去当前小区最大楼栋编号,然后加 1
            maxUnitNum++;
            //创建楼栋信息
            saveUnits.add(this.unitFactory(floor, maxUnitNum, roomNum, community,unitVo));
        }
        return unitMapper.doSaveList(saveUnits);
    }

    //单元工厂
    private Unit unitFactory(Floor floor, int unitNum, AtomicInteger floorRoomNum, Community community,UnitVo unitVo) {
        Unit bean = new Unit();
        bean.setId(IdUtils.simpleUUID());
        bean.setFloorId(floor.getId());
        bean.setUnitNum(unitNum + "");
        bean.setUnitName("第" + unitNum + "单元");
        bean.setLayerNum(unitVo.getLayerNum());
        bean.setRoomNum(unitVo.getRoomNum());
        bean.setDeptId(floor.getDeptId());
        bean.setCommunityId(floor.getCommunityId());
        bean.setCreateBy(SecurityUtils.getUsername());
        bean.setCreateTime(DateUtils.getNowDate());
        bean.setAncestors(floor.getAncestors() + "," + floor.getId());
        bean.setDataSourceId("系统创建");
        orgTreeService.insertOrgTree(bean.getId(), bean.getUnitName(), bean.getFloorId(), OrgConstants.unit, bean.getAncestors(), unitNum);
        this.roomFactory(floor, bean, community, floorRoomNum);
        return bean;
    }

    //房屋工厂
    private void roomFactory(Floor floor, Unit unit, Community community, AtomicInteger floorRoomNum) {
        List<Room> savaRooms = new ArrayList<>();
        for (Integer i = 0; i < unit.getLayerNum(); i++) {
            Integer layerNum = i + 1;//层数

            for (int j = 0; j < unit.getRoomNum(); j++) {
                Room bean = new Room();
                bean.setId(IdUtils.simpleUUID());
                bean.setUnitId(unit.getId());
                bean.setFloorId(unit.getFloorId());
                bean.setCommunityId(community.getId());
                bean.setDeptId(community.getDeptId());

                Integer roomNum = j + 1;//房间数
                String houseNum = "";
                //门牌号生成规则
                if (StringUtils.isNotEmpty(floor.getRoomRule())) {
                    if (floor.getRoomRule().equals(PropertyConstants.room_rule_10)) {
                        floorRoomNum.incrementAndGet();
                        //按照楼统一编排
                        houseNum = NumberUtils.frontCompWithZore(floorRoomNum.get(), 3);
                        bean.setRoomOrder(floorRoomNum.get());
                    } else if (floor.getRoomRule().equals(PropertyConstants.room_rule_20)) {
                        //按照楼层和房间号编排
                        houseNum = NumberUtils.frontCompWithZore(layerNum, 2) + NumberUtils.frontCompWithZore(roomNum, 2);
                        bean.setRoomOrder(roomNum);
                    }
                }

                bean.setLayerNum(layerNum + "");
                bean.setRoomNum(houseNum);
                bean.setDataSourceId("系统创建");
                bean.setStatusCd(PropertyConstants.housing_status_10001);
                bean.setCreateTime(DateUtils.getNowDate());
                bean.setCreateBy(SecurityUtils.getUsername());
                bean.setAncestors(unit.getAncestors() + "," + unit.getId());
                bean.setRoomName(floor.getFloorNum() + "-" + unit.getUnitNum() + "-" + houseNum);
                String cityName = "";
                if (StringUtils.isNotEmpty(community.getCityName())) {
                    String[] split = community.getCityName().split("/");
                    for (String s : split) {
                        cityName += s;
                    }
                }
                bean.setAddress(cityName + community.getCommunityName() + floor.getFloorName() + unit.getUnitName() + bean.getRoomNum());
                orgTreeService.insertOrgTree(bean.getId(), bean.getRoomNum(), bean.getUnitId(), OrgConstants.room, bean.getAncestors(),Integer.valueOf( bean.getRoomNum()));
                savaRooms.add(bean);
            }
        }
        roomService.doSaveList(savaRooms);

    }


    private void checkParams(UnitVo unitVo) {
        if (unitVo.getUnitNum() < 1) {
            throw new BaseException("单元数量必须大于0");
        }
        if (unitVo.getLayerNum() < 1) {
            throw new BaseException("单元层数必须大于0");
        }
        if (unitVo.getRoomNum() < 1) {
            throw new BaseException("单元户数必须大于0");
        }
    }


}
